package cn.bmbanjia.zebra2024.aliyuncloud.rocketmq.consumer;

import cn.bmbanjia.zebra2024.aliyuncloud.rocketmq.producer.BmbjProducerDelayMessage;
import cn.bmbanjia.zebra2024.apps.base.clew.entity.Clew;
import cn.bmbanjia.zebra2024.apps.base.clew.service.IClewService;
import cn.bmbanjia.zebra2024.apps.base.dispatchClewLog.entity.DispatchClewLog;
import cn.bmbanjia.zebra2024.apps.base.dispatchClewLog.service.IDispatchClewLogService;
import cn.bmbanjia.zebra2024.apps.base.user.entity.User;
import cn.bmbanjia.zebra2024.apps.base.user.service.IUserService;
import cn.bmbanjia.zebra2024.comWechat.SendMessageUtil;
import cn.bmbanjia.zebra2024.frame.util.SpringContext;
import cn.bmbanjia.zebra2024.tencentcloud.TencentCloudVMS;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.*;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.FilterExpressionType;
import org.apache.rocketmq.client.apis.consumer.PushConsumer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static cn.bmbanjia.zebra2024.apps.base.clew.entity.table.ClewTableDef.CLEW;
import static cn.bmbanjia.zebra2024.apps.base.dispatchClewLog.entity.table.DispatchClewLogTableDef.DISPATCH_CLEW_LOG;
import static cn.bmbanjia.zebra2024.apps.base.user.entity.table.UserTableDef.USER;

@Slf4j
@Component
public class BmbjClewDelayPushConsumer {

    private static final ClientServiceProvider provider = ClientServiceProvider.loadService();

    private static final SessionCredentialsProvider sessionCredentialsProvider =
            new StaticSessionCredentialsProvider("x5925u103dWR5iqy", "gXlhqv0QqD1b7b88");

    private static final ClientConfiguration clientConfiguration = ClientConfiguration.newBuilder()
            .setEndpoints("rmq-cn-8ex3ui0jj03.cn-shenzhen.rmq.aliyuncs.com:8080")
            .setNamespace("rmq-cn-8ex3ui0jj03")
            .setCredentialProvider(sessionCredentialsProvider)
            .build();

    public static String tag = "bmbj_clew";
    public static String consumerGroup = "bmbj";
    public static String[] topics = new String[]{"bmbj_clew_delay"};

    private static final FilterExpression filterExpression = new FilterExpression(tag, FilterExpressionType.TAG);

    private static PushConsumer pushConsumer;

    static {
        try {
            provider.newPushConsumerBuilder()
                    .setClientConfiguration(clientConfiguration)
                    .setConsumerGroup(consumerGroup)
                    .setSubscriptionExpressions(Collections.singletonMap(topics[0], filterExpression))
                    .setMessageListener(messageView -> {
                        try {
                            String body = StandardCharsets.UTF_8.decode(messageView.getBody()).toString();
                            log.info("BmbjClewDelayPushConsumer message body = {}", body);
                            JSONObject entries = JSONUtil.parseObj(body);

                            Integer clewId = entries.getInt("clewId");
                            Integer phoneCount = entries.getInt("phoneCount");
                            Integer dispatchClewId = entries.getInt("dispatchClewId");
                            String calledNumber = entries.getStr("calledNumber");
                            Integer userId = entries.getInt("userId");
                            String userName = entries.getStr("userName");
                            Integer cityType = entries.getInt("cityType");

                            IClewService clewService = SpringContext.getBean(IClewService.class);
                            Clew clew = clewService.getOne(QueryWrapper.create()
                                    .where(CLEW.ID.eq(clewId)));

                            if (ObjUtil.isNotNull(clew) && clew.getStatus() != 0) {
                                // 线索已经处理
                                return ConsumeResult.SUCCESS;
                            }

                            IDispatchClewLogService dispatchClewLogService = SpringContext.getBean(IDispatchClewLogService.class);

                            if (phoneCount == 1) {
                                // 第二次电话通知
                                TencentCloudVMS.sendTtsVoice(TencentCloudVMS.VOICE_SDK_APPID, calledNumber, TencentCloudVMS.TEMPLATE_ID_CLEW);

                                // 更新通知次数
                                DispatchClewLog dcl = DispatchClewLog.builder()
                                        .dispatchClewId(dispatchClewId)
                                        .phoneCount(phoneCount + 1)
                                        .updateUserId(userId)
                                        .updateUserName(userName)
                                        .build();
                                dispatchClewLogService.updateById(dcl);

                                // 继续消息队列
                                entries.set("phoneCount", phoneCount + 1);
                                BmbjProducerDelayMessage.sendBmbjClewDelayMessage(entries.toString().getBytes(StandardCharsets.UTF_8));

                            } else {
                                // 切换下一个人
                                IUserService userService = SpringContext.getBean(IUserService.class);
                                List<User> list = userService.list(QueryWrapper.create()
                                        .where(USER.STATUS.eq("0"))
                                        .where(USER.DEL_FLAG.eq("0"))
                                        .where(USER.CITY_TYPE.eq(cityType)));

                                List<Integer> userIds = dispatchClewLogService.listAs(QueryWrapper.create()
                                        .select(DISPATCH_CLEW_LOG.USER_ID)
                                        .where(DISPATCH_CLEW_LOG.CLEW_ID.eq(clewId)), Integer.class);

                                // 剔除已经指派过得人
                                for (int i = list.size() - 1; i >= 0; i--) {
                                    // 剔除高红军
                                    if (list.get(i).getUserId() == 101) {
                                        list.remove(i);
                                        continue;
                                    }

                                    for (int i1 = userIds.size() - 1; i1 >= 0; i1--) {
                                        if (list.get(i).getUserId().equals(userIds.get(i1))) {
                                            // 已经指派过了
                                            list.remove(i);
                                            break;
                                        }
                                    }
                                }

                                if (list.isEmpty()) {
                                    // 没人拉
                                    // 继续电话通知
                                    TencentCloudVMS.sendTtsVoice(TencentCloudVMS.VOICE_SDK_APPID, calledNumber, TencentCloudVMS.TEMPLATE_ID);

                                    // 三个人都不处理 联系高红军
//                                    TencentCloudVMS.sendTtsVoice(TencentCloudVMS.VOICE_SDK_APPID, "15919955259", TencentCloudVMS.TEMPLATE_ID);

                                    // 更新通知次数
                                    DispatchClewLog dcl = DispatchClewLog.builder()
                                            .dispatchClewId(dispatchClewId)
                                            .phoneCount(phoneCount + 1)
                                            .updateUserId(userId)
                                            .updateUserName(userName)
                                            .build();
                                    dispatchClewLogService.updateById(dcl);

                                    // 继续消息队列
                                    entries.set("phoneCount", phoneCount + 1);
                                    BmbjProducerDelayMessage.sendBmbjClewDelayMessage(entries.toString().getBytes(StandardCharsets.UTF_8));
                                } else {
                                    // 还有人
                                    List<Integer> userIdss = new ArrayList<>();
                                    for (User user : list) {
                                        int count = ObjUtil.defaultIfNull(user.getCycleTurnoverRate(), 0.0).intValue();
                                        for (int i = 0; i < count; i++) {
                                            userIdss.add(user.getUserId());
                                        }
                                    }
                                    int i = RandomUtil.randomInt(userIdss.size());
                                    Integer checkedUserId = userIdss.get(i);
                                    User checked = null;
                                    for (User user : list) {
                                        if (user.getUserId().equals(checkedUserId)) {
                                            checked = user;
                                            break;
                                        }
                                    }
                                    if (ObjUtil.isNotNull(checked)) {
                                        // 线索换人
                                        Clew updateClew = Clew.builder()
                                                .id(clewId)
                                                .tracker(checked.getUserName())
                                                .trackerUserId(checked.getUserId())
                                                .updateTime((int) (System.currentTimeMillis() / 1000))
                                                .updateUserId(userId)
                                                .updateUserName(userName)
                                                .build();
                                        clewService.updateById(updateClew);
                                        // 插入线索记录 开始通知
                                        DispatchClewLog dcl = DispatchClewLog.builder()
                                                .clewId(clewId)
                                                .phoneCount(1)
                                                .type(0)
                                                .userId(checked.getUserId())
                                                .userName(checked.getUserName())
                                                .createUserId(userId)
                                                .createUserName(userName)
                                                .build();
                                        dispatchClewLogService.save(dcl);

                                        TencentCloudVMS.sendTtsVoice(TencentCloudVMS.VOICE_SDK_APPID, checked.getPhonenumber(), TencentCloudVMS.TEMPLATE_ID_CLEW);

                                        //                                    Integer clewId = entries.getInt("clewId");
                                        //                                    Integer phoneCount = entries.getInt("phoneCount");
                                        //                                    Integer dispatchClewId = entries.getInt("dispatchClewId");
                                        //                                    String calledNumber = entries.getStr("calledNumber");
                                        //                                    Integer userId = entries.getInt("userId");
                                        //                                    String userName = entries.getStr("userName");
                                        //                                    Integer cityType = entries.getInt("cityType");

                                        entries.set("phoneCount", 1);
                                        entries.set("dispatchClewId", dcl.getDispatchClewId());
                                        entries.set("calledNumber", checked.getPhonenumber());

                                        String content = " 线索未联系变更跟进人 [ 名称：" + clew.getName()
                                                + "，联系方式：" + clew.getTelephone() + "，预约联系时间："
                                                + (ObjUtil.isNull(clew.getAppointmentTime()) ? "" : new DateTime(clew.getAppointmentTime() * 1000L).toString(DatePattern.NORM_DATETIME_PATTERN))
                                                + "，联系地址：" + clew.getAddress() + "，来源：" + clew.getSource() + "，备注：" + clew.getRemark() + " ] ，请及时处理。";
                                        String url = SendMessageUtil.URL_CLEW;
                                        if (StrUtil.isBlank(checked.getComWechatUserId())) {
                                            content += " 无对应工作人员openid " + checked.getUserName();
                                        }
                                        SendMessageUtil.send(content, url, checked.getComWechatUserId());

                                        BmbjProducerDelayMessage.sendBmbjClewDelayMessage(entries.toString().getBytes(StandardCharsets.UTF_8));
                                    }
                                }
                            }
                        } catch (Exception e) {
                            log.error("e: ", e);
                        }

                        return ConsumeResult.SUCCESS;
                    })
                    .build();

        } catch (ClientException e) {
            log.error("e: ", e);
        }
    }

}
